var map;
var initExtent;
var shanghaiSpatialRef;
var myFeatureTable;
var initDynamicLayer;
var convertArrayOfObjectsToCSV;

var createFeatureTable;

var dLayers = [];

var measurementFlag = false;
var measurement = null;

var selectedGraphic; // 存储点击图层选中的图形，用于弹出右键菜单,通过鼠标移入事件赋值
var ctxMenuForGraphics; // 存储点击图层选中的图形，用于弹出右键菜单
var clickQueryGraphicsLayer;
var isCtxMenu = false; //判断区域覆盖分析的触发来源，控制保存图层名称v
var identifyIdsArr = []; //存储每个动态图层哪些子图层处于打开状态，用于点击高亮时的判断
var tableLayerGraphics = []; // 存储当前打开属性表的自定义featurelayer图层的graphics，用于数据过滤
// var defaultIcon = "";

function getLayersData(MapLayerUrl) {
  var pjsonUrl = "";
  var legendJsonUrl = "";
  if (MapLayerUrl.indexOf("?token=") != -1) {
    const arr = MapLayerUrl.split("?");
    pjsonUrl = arr[0] + "?f=pjson&" + arr[1];
    legendJsonUrl = arr[0] + "/legend?f=pjson&" + arr[1];
  } else {
    pjsonUrl = MapLayerUrl + "?f=pjson";
    legendJsonUrl = MapLayerUrl + "/legend?f=pjson";
  }

  var layersArray = [];
  $.ajax({
    type: "POST",
    url: pjsonUrl,
    dataType: "json",
    async: false,
    success: function (data, textStatus, jqHXR) {
      var node = {
        name: "",
        open: false,
        chileren: [],
      };
      console.log(data);
      layersArray = data.layers;
      // const tablesArray = data.tables;
      // layersArray.push(...tablesArray)
      var treeJson = [];
      for (var i = 0; i < layersArray.length; i++) {
        if (-1 == layersArray[i]) {
          node = {
            name: layersArray[i].name,
            open: false,
          };
        }
        if (null != layersArray[i].subLayerIds) {
        }
        treeJson.push(node);
      }
    },
  });

  $.ajax({
    type: "POST",
    // url: MapLayerUrl + '/legend?f=pjson',
    url: legendJsonUrl,
    dataType: "json",
    async: false,
    success: function (data, textStatus, jqHXR) {
      var legendArray = data.layers;
      console.log(legendArray, "009989");
      for (var i = 0; i < legendArray.length; i++) {
        var layerId = legendArray[i].layerId;
        if (legendArray[i].legend.length > 1) {
          var legends = legendArray[i].legend;
          for (var k = 0; k < legends.length; k++) {
            if (typeof legends[k].imageData != "undefined") {
              var legendNode = {
                parentLayerId: layerId,
                name: legends[k].label,
                icon: "data:image/png;base64," + legends[k].imageData,
              };
              console.log(legendNode);
              layersArray.push(legendNode);
              console.log(layersArray);
            }
          }
          layersArray[layerId].icon = "";
        } else {
          if (typeof legendArray[i].legend[0].imageData != "undefined") {
            layersArray[layerId].icon =
              "data:image/png;base64," + legendArray[i].legend[0].imageData;
          }
        }
      }
    },
  });

  var rootNode = {
    id: -1,
    name: "root",
    children: [],
  };
  var data = layersArray;
  var layerArray = [];
  for (var i = 0; i < data.length; i++) {
    if (undefined == data[i].icon) {
      // data[i].icon = defaultIcon;
    }
    if (undefined == data[i].id) {
      data[i].nocheck = true;
    } else {
      data[i].nocheck = false;
    }
    // 这是头部树形结构的配置
    var title = "临港功能区";
    var node = {
      id: data[i].id,
      parentId: data[i].parentLayerId,
      open: true,
      name: data[i].name,
      icon: data[i].icon,
      nocheck: data[i].nocheck,
    };
    console.log(node);
    if (node.name == "LG_GNQ") {
      node.name = title;
    }
    layerArray.push(node);
  }

  console.log(layerArray);
  for (var i = 0; i < layerArray.length; i++) {
    if (-1 == layerArray[i].parentId) {
      rootNode.children.push(recursion(layerArray[i], layerArray));
      console.log(rootNode);
    }
  }
  return rootNode.children;
}
/**
 * 数组转换为treeJson
 */
function recursion(node, nodes) {
  for (var index = 0; index < nodes.length; index++) {
    if (node.id == nodes[index].parentId) {
      if (undefined == node.children) {
        node.children = [];
      }
      node.children.push(recursion(nodes[index], nodes));
      console.log(node, "-----");
    }
  }
  return node;
}
/**
 * 图层控制
 */
var identifyIds = [-1];

require([
  "dojo/dom",
  "esri/Color",
  "dojo/keys",
  "dojo/parser",
  "dojo/on",
  "dojo/dom-construct",
  "dojo/dom-class",
  "dojo/_base/array",
  "dojo/_base/connect",
  "dojo/_base/lang",
  "dojox/collections/Dictionary",
  "dijit/Menu",
  "dijit/MenuItem",
  "dijit/MenuSeparator",

  "esri/config",
  "esri/sniff",
  "esri/map",
  // "esri/MapView",
  "esri/SnappingManager",
  "esri/dijit/Measurement",
  "esri/dijit/FeatureTable",
  "esri/symbols/SimpleMarkerSymbol",
  "esri/symbols/SimpleLineSymbol",
  "esri/symbols/SimpleFillSymbol",
  "esri/symbols/PictureMarkerSymbol",
  "esri/renderers/ClassBreaksRenderer",

  "dijit/registry",

  "esri/layers/ArcGISDynamicMapServiceLayer",
  "esri/layers/ArcGISTiledMapServiceLayer",
  "esri/layers/FeatureLayer",
  "esri/layers/GraphicsLayer",

  "esri/dijit/HomeButton",
  "esri/dijit/Popup",
  "esri/dijit/PopupTemplate",
  "esri/units",
  "esri/SpatialReference",
  "esri/toolbars/draw",

  "esri/graphic",
  "esri/InfoTemplate",
  "esri/tasks/QueryTask",
  "esri/tasks/query",
  "esri/tasks/IdentifyTask",
  "esri/tasks/IdentifyParameters",
  "esri/tasks/IdentifyResult",
  "esri/geometry/Extent",
  "esri/geometry/Polygon",
  "esri/request",
  "esri/geometry/Point",
  "esri/geometry/Circle",
  "esri/IdentityManager",

  "esri/tasks/BufferParameters",
  "esri/tasks/GeometryService",

  "esri/dijit/Scalebar",
  "dijit/layout/BorderContainer",
  "dijit/layout/ContentPane",
  "dijit/TitlePane",
  "dijit/form/CheckBox",
  "dojo/domReady!",
], function (
  dom,
  Color,
  keys,
  parser,
  on,
  domConstruct,
  domClass,
  arrayUtils,
  connect,
  lang,
  Dictionary,
  Menu,
  MenuItem,
  MenuSeparator,
  esriConfig,
  has,
  Map,
  // MapView,
  SnappingManager,
  Measurement,
  FeatureTable,
  SimpleMarkerSymbol,
  SimpleLineSymbol,
  SimpleFillSymbol,
  PictureMarkerSymbol,
  ClassBreaksRenderer,
  registry,
  ArcGISDynamicMapServiceLayer,
  ArcGISTiledMapServiceLayer,
  FeatureLayer,
  GraphicsLayer,
  HomeButton,
  Popup,
  Units,
  PopupTemplate,
  SpatialReference,
  Draw,
  Graphic,
  InfoTemplate,
  QueryTask,
  Query,
  IdentifyTask,
  IdentifyParameters,
  IdentifyResult,
  Extent,
  Polygon,
  esriRequest,
  Point,
  Circle,
  IdentityManager,
  BufferParameters,
  GeometryService,
  Scalebar
) {
  esri.config.defaults.geometryService = new esri.tasks.GeometryService(
    geometryServiceUrl
  );

  // esriConfig.defaults.io.proxyUrl = "/proxy/proxy.jsp"
  // esriConfig.defaults.io.alwaysUseProxy = false;
  // esri.config.defaults.io.corsDection=false

  // IdentityManager.registerToken({
  //     server: oneMapServerIP+"/OneMapServer/rest/services",
  //     token: GLOBAL_TOKEN,
  //   });

  //esri初始化好后设置样式和空间参考
  shanghaiSpatialRef = new SpatialReference({
    wkt:
      'PROJCS["shanghaicity",' +
      'GEOGCS["GCS_Beijing_1954",' +
      'DATUM["D_Beijing_1954",' +
      'SPHEROID["Krasovsky_1940",6378245.0,298.3]],' +
      'PRIMEM["Greenwich",0.0],' +
      'UNIT["Degree",0.0174532925199433]],' +
      'PROJECTION["Transverse_Mercator"],' +
      'PARAMETER["False_Easting",-3457147.81],' +
      'PARAMETER["False_Northing",0.0],' +
      'PARAMETER["Central_Meridian",121.2751921],' +
      'PARAMETER["Scale_Factor",1.0],' +
      'PARAMETER["Latitude_Of_Origin",0.0],' +
      'UNIT["Meter",1.0]]',
  });

  //用于查全市的范围
  polygon = new Polygon();
  polygon.addRing([
    [-153000, -153000],
    [-153000, 153000],
    [153000, 153000],
    [153000, -153000],
    [-153000, -153000],
  ]);
  polygon.setSpatialReference(shanghaiSpatialRef);
  //设置初始范围
  initExtent = new esri.geometry.Extent();
  // initExtent.xmin = -96772;
  // initExtent.xmax = 110772;
  // initExtent.ymin = -28592;
  // initExtent.ymax = 30000;

  initExtent.xmin = 30772;
  initExtent.xmax = 45772;
  initExtent.ymin = -28592;
  initExtent.ymax = -50000;
  initExtent.setSpatialReference(shanghaiSpatialRef);

  map = new Map("map", {
    extent: initExtent,
    logo: false,
    showAttribution: false,
    showLabels: true,
    // infoWindow: popup
  });
  map.setZoom(0);
  // 查询园区图层数据
  //   $("#ceshi").click(function () {
  console.log("触发点击了");
  var query = new Query();
  query.outFields = ["*"];
  query.where = "1=1";
  query.returnGeometry = true;
  //实例化查询对象
  var queryTask = new QueryTask(
    "http://10.141.72.22:6080/arcgis/rest/services/LG_GARDEN/MapServer/0"
    // "http://10.141.72.22:6080/arcgis/rest/services/LG_AREA/MapServer/0"
  );
  //进行查询
  queryTask.execute(query, function (res) {
    console.log(res);
    var resFea = res.features;
    var htmlStr = "";
    // 拼接得到的结果进行展示
    var arrData = [];
    resFea.forEach((item, index) => {
      // htmlStr += "<li>" + item.attributes.Name + "</li>";
      htmlStr += "<li>" + item.attributes.Name + "</li>";
      arrData.push({ name: item.attributes.Name });
      var setting = {
        callback: {
          onClick: zTreeOnClick,
        },
        check: {
          enable: false,
          // chkboxType: { "Y": "ps", "N": "ps" },
          // chkboxType :{ "Y" : "sp", "N" : "ps" },
          chkStyle: "checkbox", //显示 checkbox 选择框，默认checkbox可选择值radio
        },
      };

      function zTreeOnClick(event, treeId, treeNode) {
        var uid = treeNode.id;
        console.log(treeNode, "55555");
        let NodeData = treeNode.tId;
        let flag = treeNode.checked;
        // 自定义函数进行视角飞入
        function PoZuoBiao(xValue, yValue) {
          let point = new Point({
            x: xValue, // 横坐标
            y: yValue, // 纵坐标
            spatialReference: shanghaiSpatialRef,
          });
          map.centerAndZoom(point, 5);
        }
        // 定义飞入视角的坐标数组
        let arrList = [
          {
            xValue: 34347.84307861328,
            yValue: -39822.82971191406,
          },
          {
            xValue: 43230.802893999804,
            yValue: -37150.810685999895,
          },
          {
            xValue: 32939.167348000476,
            yValue: -38493.95402299957,
          },
          {
            xValue: 43113.87012199983,
            yValue: -37128.22012000003,
          },
          {
            xValue: 43411.96492199983,
            yValue: -37211.43268500066,
          },
          {
            xValue: 42457.94589399904,
            yValue: -39756.03852699961,
          },
          {
            xValue: 43282.375293999045,
            yValue: -36694.12862699961,
          },
          {
            xValue: 43716.38846599989,
            yValue: -37786.59193700093,
          },
          {
            xValue: 41969.802673339844,
            yValue: -40968.265380859375,
          },
          {
            xValue: 35738.803283691406,
            yValue: -42923.272888183594,
          },
          {
            xValue: 37201.81094400044,
            yValue: -40338.18451100065,
          },
          {
            xValue: 32939.40887451172,
            yValue: -39208.10681152344,
          },
          {
            xValue: 39564.77090599959,
            yValue: -39031.503932999345,
          },
          {
            xValue: 43574.27366999941,
            yValue: 37413.1073410002,
          },
          {
            xValue: 44046.734160999775,
            yValue: -30811.814784000457,
          },
          {
            xValue: 25680.244662999845,
            yValue: -38246.16280521406,
          },
          {
            xValue: 30525.89373100001,
            yValue: -34354.72135400035,
          },
          {
            xValue: 42524.10290527344,
            yValue: -40698.40539550781,
          },
          {
            xValue: 44344.69733692256,
            yValue: -35881.93064099989,
          },
          {
            xValue: 43241.867936922565,
            yValue: -36908.593040999884,
          },
          {
            xValue: 41934.72303892241,
            yValue: -40554.32967399989,
          },
          {
            xValue: 43331.44360799994,
            yValue: -36931.61441599946,
          },
          {
            xValue: 43420.37190799994,
            yValue: -36954.469526000925,
          },
        ];
        for (var i = 0; i < arrList.length; i++) {
          if (NodeData == `lgyq_${i + 2}`) {
            PoZuoBiao(arrList[i].xValue, arrList[i].yValue);
          }
        }
        // switch (flag) {
        //   case true:
        //     console.log("进入")
        //     let point = new Point({
        //       x:34347.84307861328 ,// 横坐标
        //       y:-39822.82971191406, // 纵坐标
        //       spatialReference: shanghaiSpatialRef
        //     });
        //     map.centerAndZoom(point,5);
        // }
      }
      var zTreeNodes = [
        {
          name: "临港园区",
          open: true,
          children: arrData,
        }, //open:true表示默认展开
      ];
      var city = $.fn.zTree.init($("#lgyq"), setting, zTreeNodes);
    });

    // var yunquData = document.getElementById("yunquData");
    // yunquData.innerHTML = htmlStr;
  });
  var inputs = document.querySelectorAll("#yunquData input");
  console.log(inputs);

  var home = new HomeButton(
    {
      map: map,
    },
    "HomeButton"
  );
  home.startup();

  var scalebar = new Scalebar({
    map: map,
    scalebarUnit: "dual",
  });

  $("#measureButton").click(function () {
    $(":input.form-control").val("");
    var measurementDiv = document.createElement("div");
    measurementDiv.id = "measurementDiv";
    var measurementTip = document.createElement("p");
    measurementTip.id = "measurementTip";

    $("#measurePanel .panel-body").append(measurementDiv);
    $("#measurePanel .panel-body").append(measurementTip);

    measurement = new Measurement(
      {
        map: map,
        defaultAreaUnit: esri.Units.SQUARE_KILOMETERS,
        defaultLengthUnit: esri.Units.KILOMETERS,
      },
      document.getElementById("measurementDiv")
    );

    measurement.on("measure-start", function (evt) {
      document.getElementById("measurementTip").innerHTML = "双击完成测量";
    });

    measurement.on("measure-end", function (evt) {
      var name;
      if (evt.toolName === "area") {
        name = "面积";
      } else {
        name = "距离";
      }
      document.getElementById("measurementTip").innerHTML =
        "再次点击<b>" + name + "</b>按钮退出" + name + "测量功能";
    });
    measurement.startup();
    measurement.hideTool("location");

    closePanel();

    $("#measurePanel").show();

    //去除动态图层的infoTemplates，防止点击查询
    measurementFlag = true;

    closeIdentify();
  });

  $("#measurePanel .close").click(function () {
    // measurement.clearResult();
    if (measurement) {
      measurement.destroy();
      // measurement.setTool("area",false);
      // measurement.setTool("length",false);
    }
    // measurementFlag = false;
    // openIdentify();

    $("#measurePanel").hide();
  });

  initBaseMap();

  initDynamicLayer = (dLayerConfig) => {
    const layerId = dLayerConfig.layerId;
    const visible = dLayerConfig.visible || false; //原本的代码
    // const visible = dLayerConfig.visible;
    const opacity = dLayerConfig.opacity;
    const url = dLayerConfig.url;
    const zTreeDivId = dLayerConfig.zTreeDivId;
    const zTreeSearchInputId = dLayerConfig.zTreeSearchInputId;
    const zTreeCheckFun = dLayerConfig.zTreeCheckFun;
    const isZoom = dLayerConfig.isZoom || false;

    console.log(url);

    var identifyIds = {
      zTreeDivId: zTreeDivId,
      url: url,
      ids: [-1],
    };
    identifyIdsArr.push(identifyIds);
    console.log(identifyIdsArr, "&&&&");

    let infoTemplates = {};
    infoTemplatesArr.push(infoTemplates);
    console.log(infoTemplatesArr, "====");
    // infoTemplatesArr[infoTemplatesArr.length - 1];

    var dLayer = new ArcGISDynamicMapServiceLayer(url, {
      id: layerId,
      visible: visible,
      opacity: opacity,
    });
    var Fealayer = new FeatureLayer(
      "http://10.141.72.22:6080/arcgis/rest/services/LG_GARDEN/MapServer"
      // "http://10.141.72.22:6080/arcgis/rest/services/LG_AREA/MapServer"
    );

    dLayer.on("load", function (e) {
      map.addLayer(dLayer);
      map.addLayer(Fealayer);

      var layers = e.layer.layerInfos;
      var featureLayers = [];
      for (var i = 0; i < layers.length; i++) {
        var fUrl = "";
        if (url.indexOf("?token=") != -1) {
          const arr = url.split("?");
          fUrl = arr[0] + "/" + i + "?" + arr[1];
          // console.log(fUrl,"000000")
        } else {
          fUrl = url + "/" + i;
        }

        var mylayer = new FeatureLayer(fUrl, {
          mode: FeatureLayer.MODE_ONDEMAND,
          outFields: ["*"],
          visible: false,
          // opacity:0
        });
        featureLayers.push(mylayer);
        console.log(featureLayers, "^^^^");
        // map.addLayer(mylayer);

        // var selectionSymbol = new SimpleMarkerSymbol("solid", 10, null, orangeRed);
        // mylayer.setSelectionSymbol(selectionSymbol);
      }

      var zTreeObj;
      var setting = {
        // view: {
        //     selectedMulti: false,
        //     addDiyDom: addDiyDom
        // },
        check: {
          enable: true,
        },
        callback: {
          onCheck: zTreeOnCheck,
          onClick: zTreeOnClick,
        },
        view: {
          showLine: false,
        },
      };

      function zTreeOnClick(event, treeId, treeNode) {
        var uid = treeNode.id;
        // 获取到左侧四个功能区的节点数据
        console.log(treeNode, "00000");
        if (treeNode.name == "119.5") {
          console.log("119.5--", treeNode.checked);
        } else if (treeNode.name == "25.31") {
          console.log("25.31--", treeNode.checked);
        } else if (treeNode.name == "386") {
          console.log("386--", treeNode.checked);
        } else if (treeNode.name == "873") {
          console.log("873--", treeNode.checked);
        }
        var tableLayer = null;
        console.log(featureLayers, "——————————");
        for (var i = 0; i < featureLayers.length; i++) {
          if (featureLayers[i].layerId === uid) {
            tableLayer = featureLayers[i];
            console.log(tableLayer, featureLayers[i]);
          }
        }

        if (tableLayer === null) return;

        //当点击的是图层时才弹出属性表，如果是图层组不弹出
        if (tableLayer.type === "Feature Layer") {
          createFeatureTable(tableLayer);
          console.log("弹出底部框");
          // $(".esri-feature-table-menu-options").remove();
          $("#map").css("height", "63%");
          $("#result").show();
        }
      }
      function zTreeOnCheck(e, treeId, treeNode) {
        console.log("触发这里的事件了", treeNode);
        var zTree = $.fn.zTree.getZTreeObj(zTreeDivId),
          checkedNodes = zTree.getCheckedNodes(true);
        console.log(zTree, checkedNodes, "++++++");
        var ids = [];
        console.log(window.D_LAYERS);
        if (treeNode.checked) {
          console.log("图层显示");
          window.D_LAYERS[0].visible = true
        } else {
          console.log("图层隐藏");
          // dLayer.setVisibility(true)
          window.D_LAYERS[0].visible = true
        }

        if (0 < checkedNodes.length) {
          for (var i = 0; i < checkedNodes.length; i++) {
            // 如果是图层组，不加入可视图层
            if (checkedNodes[i].open === true) {
              continue;
            }

            if (!checkedNodes[i].isParent) {
              ids.push(checkedNodes[i].id);
            } else {
              if (checkedNodes[i].children.length > 0) {
                var flag = false;
                for (var k = 0; k < checkedNodes[i].children.length; k++) {
                  flag = checkedNodes[i].children[k].nocheck;
                }
                if (flag) {
                  console.log(ids, "9900");
                  ids.push(checkedNodes[i].id);
                }
              }
            }
          }
        } else {
          ids.push(-1);
        }
        console.log(ids, "---");
        identifyIdsArr.forEach((currentItem) => {
          if (currentItem.zTreeDivId == treeId) {
            currentItem.ids = ids;
          }
        });

        // identifyIds = ids;
        map.getLayer(layerId).setVisibility(true);
        map.getLayer(layerId).setVisibleLayers(ids);
      }

      function closeTree(layerListId) {
        var tree = $.fn.zTree.getZTreeObj(layerListId);

        //获取 zTree 的全部节点数据将节点数据转换为简单 Array 格式
        var nodes = tree.transformToArray(tree.getNodes());
        console.log(nodes, "$$$");
        for (var i = 0; i < nodes.length; i++) {
          if (nodes[i].level == 0) {
            // console.log(nodes[i].name);
            //根节点展开
            tree.expandNode(nodes[i], true, true, false);
          } else {
            tree.expandNode(nodes[i], false, true, false);
          }
        }
      }

      var interval1 = setInterval(function () {
        console.log("888,", zTreeSearchInputId);
        var zNodes = getLayersData(url);
        zTreeObj = $.fn.zTree.init($("#" + zTreeDivId), setting, zNodes);
        console.log(zTreeObj, zTreeDivId, "22222");
        var zTree1 = $.fn.zTree.getZTreeObj(zTreeDivId);
        // 使得四个功能区默认处于全选状态
        zTree1.checkAllNodes(true);
        // zTree1.checkAllNodes(false);

        closeTree(zTreeDivId);
        fuzzySearch(zTreeDivId, "#" + zTreeSearchInputId, null, true); //初始化模糊搜索方法

        //聚焦到自己添加的服务的第一个子图层
        //有可能遇到过大的图层打不开
        // if (isZoom) {
        //     var layerInfos = e.layer.layerInfos;

        //     for (let i = 0; i < layerInfos.length; i++) {
        //         if (layerInfos[i].subLayerIds == null) {
        //             var node = zTree1.getNodeByTId((i + 1).toString());
        //             zTree1.checkNode(node, true, true, true);
        //             break;
        //         }
        //     }
        //     map.setExtent(e.layer.initialExtent);
        // }

        window.clearInterval(interval1);
      }, 500);

      //为每个子图层设定全字段的infowindow
      for (var i = 0; i < layers.length; i++) {
        (function (arg) {
          var fUrl = "";
          if (url.indexOf("?token=") != -1) {
            const arr = url.split("?");
            fUrl = arr[0] + "/" + arg + "?" + arr[1];
            // console.log(fUrl,"111111")
          } else {
            fUrl = url + "/" + arg;
          }

          var countyFields = esriRequest({
            // url: url + "/" + arg,
            url: fUrl,
            content: {
              f: "json",
              // token: GLOBAL_TOKEN
            },
            callbackParamName: "callback",
          });
          countyFields.then(
            function (resp) {
              var fields = resp.fields;
              if (fields != null) {
                var table = "<table style='word-break: break-all;'>";

                for (var j = 0; j < fields.length; j++) {
                  if (j % 2 == 1) {
                    str =
                      "<tr><td class='leftTd'>" +
                      fields[j].alias +
                      "</td><td class='rightTd'>${" +
                      fields[j].name +
                      "}</td></tr>";
                  } else {
                    str =
                      "<tr bgcolor=\"#eeeeee\"><td class='leftTd'>" +
                      fields[j].alias +
                      "</td><td class='rightTd'>${" +
                      fields[j].name +
                      "}</td></tr>";
                  }
                  table = table + str;
                }
                table = table + "</table>";

                var template = new InfoTemplate();

                template.setTitle(resp.name);

                template.setContent(table);
                infoTemplates[arg] = {
                  infoTemplate: template,
                };
              }
            },
            function (err) {
              console.log("failed to get field names: ", err);
            }
          );
        })(i);
      }

      dLayers.push(dLayer);

      // console.log(dLayer)
      dLayer.setInfoTemplates(infoTemplates);
    });
  };

  D_LAYERS.map((dLayerConfig) => {
    initDynamicLayer(dLayerConfig);
  });

  function createDrawDataMenu() {
    ctxMenuForDrawData = new Menu({
      onOpen: function (box) {
        //当前点的位置
        currentLocation = getMapPointFromMenuPosition(box);
        map.infoWindow.hide();
        // editToolbar.deactivate();
      },
    });
    //添加子菜单栏
    ctxMenuForDrawData.addChild(
      new MenuItem({
        label: "删除当前图形",
        onClick: function (evt) {
          drawGraphicsLayer.remove(selectedDrawGraphic);
        },
      })
    );

    //小部件启动
    ctxMenuForDrawData.startup();
    //绑定父容器
    //给每个graphics添加鼠标移入事件
    drawGraphicsLayer.on("mouse-over", function (evt) {
      //获取当前鼠标悬浮的graphic
      selectedDrawGraphic = evt.graphic;

      // Let's bind to the graphic underneath the mouse cursor
      ctxMenuForDrawData.bindDomNode(evt.graphic.getDojoShape().getNode());
      // console.log(evt.graphic.getDojoShape().getNode());
    });
    //给每个graphics添加鼠标移出事件
    drawGraphicsLayer.on("mouse-out", function (evt) {
      ctxMenuForDrawData.unBindDomNode(evt.graphic.getDojoShape().getNode());
    });
  }

  //编辑等右键菜单栏函数封装
  function createGraphicsMenu() {
    // Creates right-click context menu for GRAPHICS
    ctxMenuForGraphics = new Menu({
      onOpen: function (box) {
        //当前点的位置
        currentLocation = getMapPointFromMenuPosition(box);
        map.infoWindow.hide();
        // editToolbar.deactivate();
      },
    });
    ctxMenuForGraphics.addChild(
      new MenuItem({
        label: "覆盖范围分析",
        onClick: function () {
          closePanel();

          isCtxMenu = true;

          $("#areaCoveragePanel").show();
          $("#bufferInput").focus();

          // setBufferParams([selectedGraphic.geometry]);
          setBufferParams([selectedGraphic]);
        },
      })
    );

    ctxMenuForGraphics.addChild(
      new MenuItem({
        label: "影像对比分析",
        onClick: function () {
          closePanel();

          $("#imageComparePanel").show();
          // $("#imageComparePanel").css("height", 300);
          $("#imageCompareRow2").hide();
          addToMap(selectedGraphic);
        },
      })
    );

    ctxMenuForGraphics.addChild(
      new MenuItem({
        label: "属性计算",
        onClick: function () {
          closePanel();
          $("#attrLabel1").text("");
          $("#attrLabel2").text("");

          var selectedArea;
          var selectedLength;
          if (selectedGraphic.geometry.type == "polygon") {
            // selectedArea = selectedGraphic.attributes."st_area(shape)";
            selectedArea = selectedGraphic.attributes["st_area(shape)"];
            selectedLength = selectedGraphic.attributes["st_length(shape)"];
            selectedArea = parseFloat(selectedArea).toFixed(2);
            selectedLength = parseFloat(selectedLength).toFixed(2);

            $("#attrLabel1").text("面积为：" + selectedArea + "平方米");
            $("#attrLabel2").text("周长为：" + selectedLength + "米");
            console.log(selectedGraphic);
          } else if (selectedGraphic.geometry.type == "polyline") {
            selectedLength = selectedGraphic.attributes["st_length(shape)"];
            selectedLength = parseFloat(selectedLength).toFixed(2);

            $("#attrLabel1").text("周长为：" + selectedLength + "米");

            console.log(selectedGraphic);
          }
          $("#attrCalPanel").show();
        },
      })
    );

    ctxMenuForGraphics.addChild(
      new MenuItem({
        label: "反向地址检索",
        onClick: function () {
          closePanel();

          $("#gAroundPanel").show();

          setAroundParams([selectedGraphic]);
        },
      })
    );

    ctxMenuForGraphics.startup();

    //给每个graphics添加鼠标移入事件
    clickQueryGraphicsLayer.on("mouse-over", function (evt) {
      //获取当前鼠标悬浮的graphic
      selectedGraphic = evt.graphic;

      // Let's bind to the graphic underneath the mouse cursor
      ctxMenuForGraphics.bindDomNode(evt.graphic.getDojoShape().getNode());
      // console.log(evt.graphic.getDojoShape().getNode());
    });
    //给每个graphics添加鼠标移出事件
    clickQueryGraphicsLayer.on("mouse-out", function (evt) {
      ctxMenuForGraphics.unBindDomNode(evt.graphic.getDojoShape().getNode());
    });

    bufferGraphicsLayer.on("mouse-over", function (evt) {
      //获取当前鼠标悬浮的graphic
      selectedGraphic = evt.graphic;

      // Let's bind to the graphic underneath the mouse cursor
      ctxMenuForGraphics.bindDomNode(evt.graphic.getDojoShape().getNode());
      // console.log(evt.graphic.getDojoShape().getNode());
    });
    //给每个graphics添加鼠标移出事件
    bufferGraphicsLayer.on("mouse-out", function (evt) {
      ctxMenuForGraphics.unBindDomNode(evt.graphic.getDojoShape().getNode());
    });
  }

  function getMapPointFromMenuPosition(box) {
    var x = box.x,
      y = box.y;
    switch (box.corner) {
      case "TR":
        x += box.w;
        break;
      case "BL":
        y += box.h;
        break;
      case "BR":
        x += box.w;
        y += box.h;
        break;
    }
    var screenPoint = new Point(x - map.position.x, y - map.position.y);
    return map.toMap(screenPoint);
  }

  map.on("load", function () {
    clickQueryGraphicsLayer = new GraphicsLayer({
      id: "clickQueryGraphicsLayer",
    });
    map.addLayer(clickQueryGraphicsLayer, -1);

    // createMapMenu();

    initBufferCal();
    initAddLocalData();
    initImageCompare();
    initAddressSearch();
    initAroundSearch();
    initDrawData();

    createGraphicsMenu();
    createDrawDataMenu();
  });

  // map.on("zoom-end", function (e) {
  //     if (map.getScale() <= 50000) {

  //         var zTree1 = $.fn.zTree.getZTreeObj('clusterLayerList');
  //         var subNodes = zTree1.getNodes()[0].children;
  //         if (subNodes) {
  //             subNodes.forEach(item => {
  //                 if (item.name.endWith("的聚合图")) {
  //                     layerId = item.layerId;
  //                     // map.getLayer(layerId).graphics = clusterGraphicsObj[layerId];
  //                     // map.getLayer(layerId).redraw();
  //                 }
  //             })
  //         }
  //     } else {
  //         var zTree1 = $.fn.zTree.getZTreeObj('clusterLayerList');
  //         var subNodes = zTree1.getNodes()[0].children;
  //         if (subNodes) {
  //             subNodes.forEach(item => {
  //                 if (item.name.endWith("的聚合图")) {
  //                     layerId = item.layerId;
  //                     // map.getLayer(layerId).setDefinitionExpression("类型 = '区县'");
  //                     // map.getLayer(layerId).redraw();
  //                 }
  //             })
  //         }
  //     }
  // });

  map.on("click", function (evt) {
    var interval = setInterval(function () {
      if ($(".esriPopup .contentPane")[0].childNodes.length > 0) {
        var text = $(".esriPopup .contentPane")[0].childNodes[0].innerHTML;
        if (text == "无任何可用信息.") {
          map.infoWindow.hide();
        }
      }

      // console.log(SJJlayer);
      window.clearInterval(interval);
    }, 500);

    if (measurementFlag) {
      //测量时，屏蔽点击事件
      return;
    }

    clickQueryGraphicsLayer.clear();

    identifyIdsArr.forEach((item) => {
      var url = item.url;
      var ids = item.ids;

      identifyQuery(url, ids, evt.mapPoint, function (results, map) {
        // clickQueryGraphicsLayer.clear();
        if (results.length > 0) {
          // 利用hashtable进行对应的生成，获取相同名称的属性值，并放到同一个key对应的value中
          var hashtable = new Dictionary();
          // 这里生成新的数组，获取名字相同的图层名
          for (var i = 0; i < results.length; i++) {
            if (!hashtable.containsKey(results[i].layerName)) {
              hashtable.add(results[i].layerName, [results[i].feature]);
            } else {
              var arrayFeature = hashtable.item(results[i].layerName);
              arrayFeature.push(results[i].feature);
            }
            addGraphicsToMap(
              results[i].feature.geometry,
              results[i].feature.attributes
            );
          }
        } else {
          // alert("当前点未查询到任何元素");
        }
      });
    });
  });

  function addGraphicsToMap(geometry, attributes) {
    var symbol = null;
    switch (geometry.type) {
      case "point":
        symbol = new SimpleMarkerSymbol(
          SimpleMarkerSymbol.STYLE_SQUARE,
          14,
          new SimpleLineSymbol(
            SimpleLineSymbol.STYLE_SOLID,
            new Color([0, 255, 255]),
            2
          ),
          new Color([0, 255, 0, 0])
        );
        break;
      case "polyline":
        symbol = new SimpleLineSymbol(
          SimpleLineSymbol.STYLE_SOLID,
          new Color([0, 255, 255, 1]),
          4
        );
        break;
      case "polygon":
        symbol = new SimpleFillSymbol(
          SimpleFillSymbol.STYLE_SOLID,
          new SimpleLineSymbol(
            SimpleLineSymbol.STYLE_SOLID,
            new Color([0, 255, 255]),
            1
          ),
          new Color([255, 255, 255, 0.2])
        );
        break;
    }
    var _graphic = new Graphic(geometry, symbol, attributes);
    clickQueryGraphicsLayer.add(_graphic);
    map.removeLayer(clickQueryGraphicsLayer);
    map.addLayer(clickQueryGraphicsLayer, -1);
  }

  function identifyQuery(url, layerIds, geometry, bufferCallback) {
    var identifyTask = new IdentifyTask(url);
    var identifyParams = new IdentifyParameters();
    identifyParams.returnGeometry = true;
    identifyParams.tolerance = 5;
    identifyParams.layerIds = layerIds;
    // identifyParams.layerOption = IdentifyParameters.LAYER_OPTION_VISIBLE;
    identifyParams.layerOption = IdentifyParameters.LAYER_OPTION_TOP;
    identifyParams.geometry = geometry;
    identifyParams.width = map.width;
    identifyParams.height = map.height;
    identifyParams.mapExtent = map.extent;
    identifyParams.spatialReference = map.spatialReference;
    identifyTask.execute(
      identifyParams,
      lang.hitch(this, function (results) {
        if (lang.isFunction(bufferCallback)) {
          bufferCallback(results, map);
        }
      }),
      function (err) {}
    );
  }

  function initBaseMap() {
    BASE_LAYERS.forEach((item, index) => {
      const layerId = item.layerId;
      const name = item.name;
      const url = item.url;
      const visible = item.visible;

      var tiledMapServiceLayer = new ArcGISTiledMapServiceLayer(url, {
        id: layerId,
        visible: visible,
      });
      tiledMapServiceLayer.setScaleRange(500000, 500);
      map.addLayer(tiledMapServiceLayer);

      let li = `<li>
                <a href="#" id="${layerId}Btn">
                    <label>
                    ${name}
                    </label>
                </a>
            </li>`;
      $("#baseMapList").append(li);

      if (visible === true) {
        $(`#${layerId}Btn`).addClass("active");
      }

      $(`#${layerId}Btn`).on("click", function () {
        BASE_LAYERS.forEach((item) => {
          const layerId = item.layerId;
          $(`#${layerId}Btn`).removeClass("active");

          map.getLayer(layerId).setVisibility(false);
        });

        map.getLayer(layerId).setVisibility(true);
        $(`#${layerId}Btn`).addClass("active");
      });
    });
  }

  //属性表部分
  $("#resultClose").click(function () {
    $("#result").hide();
    $("#map").css("height", "100%");
    clickQueryGraphicsLayer.clear();
    myFeatureTable.params.featureLayer.graphics = tableLayerGraphics;
    myFeatureTable.params.featureLayer.refresh();
    myFeatureTable.params.featureLayer.redraw();
    myFeatureTable.destroy();
  });

  createFeatureTable = (tableLayer) => {
    $("#tableSearchSelect").empty();
    $("#tableSearchInput").val("");

    let initFeatureTable = () => {
      const myTableNode = document.createElement("div");
      myTableNode.id = "myTableNode";
      $("#result").append(myTableNode);

      //字段选择的下拉框赋值
      let fields = tableLayer.fields;

      fields.map((item) => {
        if (item.type != "esriFieldTypeGeometry") {
          const field = item.name;
          const label = item.alias;
          const fieldType = item.type;
          const option =
            "<option fieldType=" +
            fieldType +
            " value=" +
            field +
            ">" +
            label +
            "</option>";
          $("#tableSearchSelect").append(option);
        }
      });

      myFeatureTable = new FeatureTable(
        {
          featureLayer: tableLayer,
          map: map,
          batchCount: 100, //初始化显示多少条记录，多了会卡
          showAttachments: true,
          // only allows selection from the table to the map
          syncSelection: true,
          zoomToSelection: true,
          gridOptions: {
            allowSelectAll: true,
            allowTextSelection: true,
          },
          editable: false,
          dateOptions: {
            // set date options at the feature table level
            // all date fields will adhere this
            datePattern: "MMMM d, y",
          },
          // define order of available fields. If the fields are not listed in 'outFields'
          // then they will not be available when the table starts.
          fieldInfos: [
            {
              name: "st_area(shape)",
              alias: "面积（平方米）",
              // editable: false //disable editing on this field
            },
            {
              name: "st_length(shape)",
              alias: "周长（米）",
              // format: {
              //     template: "${value} mph" //add mph at the of the value
              // }
            },
            {
              name: "type",
              alias: "Vehicle Type",
            },
            {
              name: "unitname",
              alias: "Unit Name",
            },
          ],
          menuFunctions: [
            //Add new Export to CSV menu function
            {
              label: "导出为CSV文件",
              callback: customExportCSV,
            },
          ],
        },
        "myTableNode"
      );
      myFeatureTable.startup();

      // 存储当前featurelayer的graphics，用于过滤筛选
      tableLayerGraphics = tableLayer.graphics;

      // 点击表格行，地图聚焦对应的要素  这是功能区四个区域 表格里的内容展示
      myFeatureTable.on("row-select", function (evt) {
        console.log("row-select", evt);
        let selectedRows = evt.rows;
        let keyField, keyValue;

        map.infoWindow.clearFeatures();
        map.infoWindow.hide();

        var columns = myFeatureTable.columns;

        columns.forEach((item) => {
          if (item.type == "esriFieldTypeOID") {
            keyField = item.field;
          }
        });

        // for (var key in selectedRows[0].data) {
        //     if (key.toUpperCase() == "OBJECTID") {
        //         keyField = key;
        //         break;
        //     } else if (key.toUpperCase() == "FID") {
        //         keyField = key;
        //         break;
        //     }
        // }

        if (tableLayer.url != null) {
          let queryStr = "";
          selectedRows.forEach((item, index) => {
            let data = item.data;
            keyValue = data[keyField];
            if (index == 0) {
              queryStr += keyField + " = " + keyValue;
            } else {
              queryStr += " or " + keyField + " = " + keyValue;
            }
          });

          var query = new Query();
          query.where = queryStr;
          tableLayer.selectFeatures(
            query,
            FeatureLayer.SELECTION_NEW,
            function (result) {
              clickQueryGraphicsLayer.clear();
              result.forEach((item) => {
                // 展示功能区的 区域
                addGraphicsToMap(item.geometry, item.attributes);

                // map.infoWindow.hide();
                // map.infoWindow.setContent(item.getContent());
                // map.infoWindow.setTitle(item.getTitle());
                // map.infoWindow.show(item.geometry);
              });
            }
          );
        } else {
          let graphics = tableLayer.graphics;
          clickQueryGraphicsLayer.clear();

          selectedRows.forEach((item, index) => {
            let data = item.data;
            keyValue = data[keyField];
          });

          graphics.forEach((item, index) => {
            if (item.attributes[keyField] == keyValue) {
              addGraphicsToMap(item.geometry, item.attributes);

              // map.infoWindow.hide();
              // map.infoWindow.setContent(item.getContent());
              // map.infoWindow.setTitle(item.getTitle());
              // map.infoWindow.show(item.geometry);
            }
          });
        }
      });
    };

    if (myFeatureTable === undefined) {
      initFeatureTable();
    } else {
      myFeatureTable.params.featureLayer.graphics = tableLayerGraphics;

      myFeatureTable.destroy();

      initFeatureTable();
    }

    //防止输入中文还在打字时触发搜索
    var tableFalg = true;

    //先解绑事件，再重新绑定，防止触发多次
    $("#tableSearchInput").off("compositionstart");
    $("#tableSearchInput").on("compositionstart", function () {
      tableFalg = false;
    });
    $("#tableSearchInput").off("compositionend");
    $("#tableSearchInput").on("compositionend", function () {
      tableFalg = true;
    });
    $("#tableSearchInput").off("input");
    $("#tableSearchInput").on("input", function () {
      setTimeout(() => {
        if (tableFalg) {
          let keywords = $(this).val();
          let field = $("#tableSearchSelect").val();
          let type = $("#tableSearchSelect")
            .find("option:selected")
            .attr("fieldtype");

          //服务构成的featurelayer可以用setDefinitionExpression过滤
          if (tableLayer.url != null) {
            let sql;
            if (keywords == "") {
              sql = "1=1";
            } else {
              if (type == "esriFieldTypeString") {
                sql = field + " like '%" + keywords + "%'";
              } else {
                sql = field + " = " + keywords;
              }
            }
            tableLayer.setDefinitionExpression(sql);
            myFeatureTable.refresh();
          } else {
            //自定义featurelayer，通过控制graphics数组，控制featurelayer的数据
            // $("#"+tableLayer.id+"_layer").empty();

            if (keywords == "") {
              tableLayer.graphics = tableLayerGraphics;
              tableLayer.redraw();
            } else {
              if (type == "esriFieldTypeString") {
                let filterGraphics = tableLayerGraphics.filter((graphic) => {
                  if (graphic.attributes[field]) {
                    return graphic.attributes[field].indexOf(keywords) > -1;
                  } else {
                    return false;
                  }
                });
                // console.log(tableLayer)
                tableLayer.graphics = filterGraphics;
                // tableLayer._mode._featureMap = filterGraphics
                // tableLayer.refresh()

                // tableLayer.redraw()
              } else {
                let filterGraphics = tableLayerGraphics.filter((graphic) => {
                  if (graphic.attributes[field]) {
                    return graphic.attributes[field].indexOf(keywords) > -1;
                  } else {
                    return false;
                  }
                });
                tableLayer.graphics = filterGraphics;
                // tableLayer._mode._featureMap = filterGraphics

                // tableLayer.refresh()
                // tableLayer.redraw()
              }
            }
            myFeatureTable.refresh();
          }
        }
      }, 100);
    });

    function customExportCSV(evt) {
      //var gridData = myFeatureTable.selectedRows;
      var data = myFeatureTable.dataStore.data;

      if (typeof myFeatureTable.dataStore.layer != "undefined") {
        var tableName = myFeatureTable.dataStore.layer._name;
      } else {
        var tableName = localFileName;
      }

      var csv = convertArrayOfObjectsToCSV({
        data: data,
      });

      // if (!csv.match(/^data:text\/csv/i)) {
      //     //在csv内容前增加\ufeff，可防止excel打开时中文乱码
      //     csv = 'data:text/csv;charset=utf-8,\ufeff' + csv;
      // }

      // var encodedUri = encodeURI(csv);
      // var link = document.createElement('a');
      // link.setAttribute('href', encodedUri);
      // link.setAttribute('download', tableName + ".csv");
      // link.click();

      csv = "\ufeff" + csv;

      var blob = new Blob([csv], {
        type: "text/plain;charset=utf-8",
      });
      saveAs(blob, tableName + ".csv");
    }

    convertArrayOfObjectsToCSV = function (value) {
      var result, ctr, columnDelimiter, lineDelimiter, data;
      var keys = [];
      data = value.data || null;
      if (data == null || !data.length) {
        return null;
      }

      columnDelimiter = value.columnDelimiter || ",";
      lineDelimiter = value.lineDelimiter || "\n";

      a = data[1];

      //有些data结果的数组索引不是从0开始。。
      // var firstId=myFeatureTable.layerInfo.cachedIds[0];
      // keys = Object.keys(data[firstId].attributes);

      //获取所有的字段，构建字段数组
      var columns = myFeatureTable.columns;
      columns.forEach((item) => {
        var field = item.field;
        keys.push(field);
      });

      result = "";
      result += keys.join(columnDelimiter);
      result += lineDelimiter;

      data.forEach(function (item) {
        ctr = 0;
        keys.forEach(function (key) {
          if (ctr > 0) {
            result += columnDelimiter;
          }
          if (typeof item.attributes == "undefined") {
            if (key == "原始地址") {
              result += item[key].trim();
            } else {
              result += item[key];
            }
          } else {
            // result += item.attributes[key].trim();
            result += item.attributes[key];
          }
          // result += item[key].attributes;
          ctr++;
        });
        result += lineDelimiter;
      });

      return result;
    };
  };
});

function openIdentify() {
  dLayers.forEach((item, index) => {
    item.infoTemplates = infoTemplatesArr[index];
  });
}

function closeIdentify() {
  dLayers.forEach((item) => {
    item.infoTemplates = null;
  });
}
